<template>
  <div class="ios">
    <div class="w-full h-[77px] flex justify-center items-center flex-col">
      <div class="text-[14px] font-bold">{{ Info.name }}</div>
      <div class="mt-[5px] text-[10px]">由{{ Info.brand }}承保</div>
    </div>
    <div>
      <insureTitle title="保险日期"></insureTitle>
      <div class="p-[15px]">
        <div class="flex items-center justify-between" @click="openPicker(0)">
          <div class="flex text-[14px]">
            <div>生效日期</div>
            <div class="ml-[50px]">
              {{ startTimer ? startTimer : year + "-" + month + "-" + strDate }}
              00:00:00
            </div>
          </div>
          <div>
            <img :src="getAssetsFile('home/date.png')" class="w-[14px] h-[14px]" />
          </div>
        </div>
        <div class="border-b border-[#ECECEC] my-[15px]"></div>
        <div class="flex items-center justify-between text-[#c8c9cc]">
          <div class="flex text-[14px]">
            <div>结束日期</div>
            <div class="ml-[50px]">
              <!-- {{ endTimer ? endTimer : year + "-" + month + "-" + strDate }} -->

              <!-- 23:59:59 -->
              {{ endTimer ? endTimer + " 23:59:59" : "" }}
            </div>
          </div>
          <div>
            <img :src="getAssetsFile('home/date.png')" class="w-[14px] h-[14px]" />
          </div>
        </div>
        <div class="border-b border-[#ECECEC] my-[15px]"></div>
        <div class="flex items-center justify-between" @click="openPicker(2)">
          <div class="flex text-[14px]">
            <div>有效天数</div>
            <div class="ml-[50px]" :class="edit == true ? '' : 'text-[#c8c9cc]'">
              {{ days ? days : "请选择" }}
            </div>
          </div>
          <div>
            <img :src="getAssetsFile('home/date.png')" class="w-[14px] h-[14px]" />
          </div>
        </div>
      </div>
    </div>
    <div>
      <van-form ref="formRef" label-width="98">
        <van-cell-group inset>
          <div>
            <insureTitle title="投保人信息"></insureTitle>
            <tbrxx
              ref="tbrxxRef"
              :infoTbrxx="infoTbrxx"
              :Info="Info"
              :edit="edit"
              :addInfo="Info"
            ></tbrxx>
          </div>
          <div>
            <insureTitle title="职业类别"></insureTitle>
            <category
              ref="categoryRef"
              :category="categoryArr"
              :Info="infoCategory"
              :edit="edit"
            ></category>
          </div>
          <div>
            <insureTitle title="施工地址"></insureTitle>
            <addressVue ref="addressVueRef" :edit="edit" :addInfo="param"></addressVue>
          </div>
          <div>
            <insureTitle title="保险责任"></insureTitle>
            <responsibility
              :duty="Info.duty"
              :start_time="startTimer"
              :end_time="endTimer"
              ref="responsibilityRef"
              :edit="edit"
              :param="param"
              @change="change"
              :personCost="personCost"
            ></responsibility>
          </div>
          <div>
            <insureTitle title="被保人清单"></insureTitle>
            <user :user="param.user" :edit="edit" ref="userRef"></user>
          </div>
          <div v-if="route.query.order_id && Info.state == '2'">
            <insureTitle title="保单信息"></insureTitle>
            <bdProfile :bdInfo="Info" @getInfo="getInfo"></bdProfile>
          </div>
        </van-cell-group>
        <div
          class="flex px-[15px] pb-[15px]"
          v-if="(routeType == '1' || routeType == '3') && edit == true"
        >
          <div @click="checked = !checked" class="mt-[2px]">
            <img
              v-if="checked"
              :src="getAssetsFile('insure/active.png')"
              class="min-w-[14px] h-[14px]"
            />
            <img
              v-else
              :src="getAssetsFile('insure/noactive.png')"
              class="min-w-[14px] h-[14px]"
            />
          </div>
          <div class="ml-[10px] text-[14px]">
            购买前，请仔细阅读<span class="text-[#EF6800]" @click="clickPush(1)"
              >《投保须知》</span
            ><span class="text-[#EF6800]" @click="clickPush(2)">《特别约定》</span
            ><span class="text-[#EF6800]" @click="clickPush(3)">《产品条款》</span
            ><span class="text-[#EF6800]" @click="clickPush(4)">《保单样本》</span>
          </div>
        </div>
        <!-- 填写投保信息 -->
        <div class="w-full h-[60px] flex items-center ios" v-if="routeType == '3'">
          <div
            class="flex-1 text-[#f3a140] font-bold flex justify-center items-center h-[60px] text-[20px]"
          >
            ￥{{ cost.toFixed(2) }}
          </div>
          <div class="flex items-center justify-center px-[15px] flex-1" @click="share">
            <img :src="getAssetsFile('home/share.png')" class="w-[16px] h-[16px]" />
            <div class="text-[14px] text-[#636363] ml-[5px]">分享</div>
          </div>
          <div
            @click="openNotice"
            class="h-[60px] flex-1 flex justify-center items-center text-white"
            style="background: linear-gradient(180deg, #f3a140 0%, #f38e40 100%)"
          >
            立即投保
          </div>
        </div>
        <!-- 修改投保信息 -->
        <div
          class="w-full h-[60px] flex items-center ios"
          v-if="route.query.order_id && routeType == '1'"
        >
          <div
            class="flex-1 text-[#f3a140] font-bold flex justify-center items-center h-[60px] text-[20px]"
          >
            ￥{{ cost.toFixed(2) }}
          </div>
          <div class="flex items-center justify-center mx-[15px] flex-1" @click="Edit">
            <div class="text-[#636363] ml-[5px]">修改</div>
          </div>
          <div
            @click="pay"
            class="h-[60px] flex-1 flex justify-center items-center text-white"
            style="background: linear-gradient(180deg, #f3a140 0%, #f38e40 100%)"
          >
            <span>{{ edit ? "提交保单" : "确认支付" }}</span>
          </div>
        </div>
      </van-form>
    </div>
    <van-popup v-model:show="showBottom" position="bottom" safe-area-inset-bottom>
      <van-date-picker
        v-if="type == 0"
        title="选择日期"
        :filter="filter"
        v-model="currentDate"
        @cancel="showBottom = false"
        @confirm="pickerConfirm"
        @change="pickerChnage"
      />
      <van-picker
        v-if="type == 2"
        title="有效天数"
        :columns="dataSelect"
        @confirm="pickerConfirm"
        @cancel="showBottom = false"
      />
    </van-popup>
    <!-- 条款 -->
    <div>
      <van-popup
        round
        v-model:show="articleShow"
        position="center"
        safe-area-inset-bottom
      >
        <div
          v-for="item in Info.doc"
          class="rounded-[10px] p-[10px]"
          @click="clickArticle(item, 3)"
        >
          <div class="text-[14px] text-blue-300">{{ item.title }}</div>
        </div>
      </van-popup>
    </div>
    <!-- 遮阳罩 -->
    <div>
      <van-overlay :show="overlayShow" />
    </div>
    <!-- 投保须知弹窗 -->
    <div>
      <van-popup
        round
        v-model:show="noticeShow"
        position="center"
        safe-area-inset-bottom
        :close-on-click-overlay="false"
      >
        <div class="rounded-[10px] px-[10px] pt-[10px] pb-[60px] h-[400px] relative">
          <div class="flex justify-center items-centern font-bold text-[20px]">
            投保须知
          </div>
          <div class="" v-html="Info.notice"></div>
          <div
            class="bg-white flex justify-center items-center sticky bottom-0 py-[10px]"
          >
            <van-button type="primary" :disabled="dialogTime > 0" @click="sumbit"
              >我已全部阅读<span v-if="dialogTime">（{{ dialogTime }}s）</span>
            </van-button>
          </div>
        </div>
      </van-popup>
    </div>
  </div>
</template>
<script setup lang="ts">
import insureTitle from "./insureTitle.vue"; //标题
import tbrxx from "./tbrxx.vue"; //投保人信息
import category from "./category.vue"; //职业类别
import responsibility from "./responsibility.vue"; //保险责任
import upload from "./upload.vue";
import bdProfile from "./bdProfile.vue"; //保单信息
import user from "./user.vue"; //被保人清单
import fjInsured from "./fjInsured.vue"; //附加被保人
import addressVue from "./address.vue";
import getAssetsFile from "@/utils/getImageurl";
import { showToast, type FormInstance } from "vant";
import { ref, computed, reactive, watchEffect } from "vue";
import { useRouter, useRoute, onBeforeRouteLeave } from "vue-router";
import ys from "./ys.vue"; //标的要素
import {
  getInsureInfo,
  addOrder,
  orderDetail,
  getJobClassify,
  submitApi,
} from "@/utils/api";
import * as rrweb from "rrweb";
import { listenerHandler } from "_@rrweb_types@2.0.0-alpha.16@@rrweb/types";
const router = useRouter();
const route = useRoute();
const showBottom = ref(false);
const dialogTime = ref(5);
const type = ref(0); //0是选择生效时间 2是选择有效天数
const routeType = ref("3"); //1是去支付，2是查看详情 3是投保
const startTimer = ref("");
const noticeShow = ref(false); //投保须知弹窗
const endTimer = ref("");
const year = ref<number>();
const month = ref<number>();
const cost = ref(0);
const dataSelect = ref([
  { text: "1天", value: "1" },
  { text: "3天", value: "3" },
  { text: "7天", value: "7" },
  { text: "15天", value: "15" },
  { text: "30天", value: "30" },
  { text: "60天", value: "60" },
  { text: "90天", value: "90" },
  { text: "180天", value: "180" },
  { text: "365天", value: "365" },
]);
const overlayShow = ref(false);
const articleShow = ref(false);
const strDate = ref<number>();
const days = ref<number>(0) as any; //有效天数
const checked = ref(false); //投保须知选中
const formRef = ref<FormInstance>();
const edit = ref(true); //是否可以修改
const param = reactive<sumbitType>({
  id: "",
  bx_id: "", //保险id
  start_time: "", //开始时间
  end_time: "", //结束时间
  insure: {
    name: "", //投保人名称
    card_type: "", //投保人证件类型
    card_no: "", //投保人证件号
    contact: "", //投保人联系人
    contact_mobile: "", //投保人联系人手机号
    mailbox: "", //邮箱
    insure_type: "",
    address: ""
  },
  insured: [],
  treetop: {
    type: "",
    name: "",
    structure: "",
    area_num: "",
    province: "",
    city: "",
    area: "",
    address_id: "",
    room_no: "",
    fanan: "",
    address: "",
  },
  duty: [] as any[],
  annex: [],
  user: [],
  card_type: "",
  job_code: "",
  province: "",
  city: "",
  area: "",
  address: "",
  province_code: "",
  city_code: "",
  area_code: "",
  add_price: 0,
  is_show: "1",
  mark:[] as any
});
const filterYear = ref();
const filterMonth = ref();
const filterDay = ref();
const price = ref(0); //保险责任总保费
const Rate = ref<number>(0); //费率
//获取投保页信息
const Info = ref({} as any);
const infoTbrxx = reactive<infoTbrxxType>({
  name: "",
  card_type: "",
  card_no: "",
  contact: "",
  contact_mobile: "",
  mailbox: "",
  insure_type: "",
  address: ""
});
const infoCategory = reactive<categoryInfoType>({
  job_code: "",
  category: "",
});
const personCost = ref<number>(0); //个人保费
const categoryArr = ref([]); //职业类别回显数据
//const userArr = ref([]); //被保人清单回显数据
const tbrxxRef = ref<InstanceType<typeof tbrxx>>();
const userRef = ref<InstanceType<typeof user>>();
const categoryRef = ref<InstanceType<typeof category>>();
const fjInsuredRef = ref<InstanceType<typeof fjInsured>>();
const ysRef = ref<InstanceType<typeof ys>>();
const addressVueRef = ref<InstanceType<typeof addressVue>>();
const responsibilityRef = ref<InstanceType<typeof responsibility>>();
const uploadRef = ref<InstanceType<typeof upload>>();
const currentDate = computed(() => {
  return getDate();
});
onBeforeRouteLeave(() => {
  if (!route.query.order_id) {
    setSession();
  }
  if (stopFun) {
    stopFun();
  }
  param.mark = [];
});
let stopFun: listenerHandler | undefined;
//开始录制
const player = () => {
  let stop = rrweb.record({
    emit(event: any) {
      if(param.mark)
      param.mark.push(event);
    },
  });
  stopFun = stop;
};
const Edit = () => {
  edit.value = true;
  player();
}
const openNotice = () => {
  if (!checked.value) return showToast("请阅读协议");
  noticeShow.value = true;
  countDown();
};
//倒计时
const countDown = () => {
  let t = setInterval(() => {
    if (dialogTime.value > 0) {
      dialogTime.value--;
    }

    if (dialogTime.value <= 0) {
      clearInterval(t);
    }
  }, 1000);
};

//缓存数据
const setSession = () => {
  setParam();
  sessionStorage.setItem("zj_dqyw", JSON.stringify(param));
};
watchEffect(() => {
  if (param.user.length > 0) {
    // console.log(cost.value, param.user.length);
    countCost();
    //cost.value = cost.value * param.user.length;
  }
  if (responsibilityRef.value?.list) {
    price.value = 0;
    Rate.value = costRate() as number;
    responsibilityRef.value?.list.forEach((item: any) => {
      price.value += Number(item.price);
    });

    countCost();
  }
});
//子组件计算保费
const change = (value: Array<any>) => {
  price.value = 0;
  value.forEach((item: any) => {
    price.value += Number(item.price);
  });
  Rate.value = costRate() as number;
  // let add_price = responsibilityRef.value?.add_price as number;
  countCost();
  // console.log(param.user.length);
};
//计算费率
const costRate = () => {
  // console.log(days.value);
  // console.log(days.value);

  if (days.value <= 0) {
    return 0;
  } else if (days.value == 1) {
    return 0.03;
  } else if (days.value >= 2 && days.value <= 3) {
    return 0.06;
  } else if (days.value >= 4 && days.value <= 7) {
    return 0.1;
  } else if (days.value >= 8 && days.value <= 15) {
    return 0.12;
  } else if (days.value >= 16 && days.value <= 30) {
    return 0.2;
  } else if (days.value >= 31 && days.value <= 60) {
    return 0.3;
  } else if (days.value >= 61 && days.value <= 90) {
    return 0.4;
  } else if (days.value >= 91 && days.value <= 180) {
    return 0.7;
  } else if (days.value >= 181 && days.value <= 365) {
    return 1;
  }
};
//计算保费
const countCost = () => {
  cost.value =
    (price.value * Rate.value + Number(param.add_price)) * param.user.length;
  personCost.value = price.value * Rate.value;
  // console.log(param.user.length);
};
const clickPush = (type: number) => {
  // let param = {
  //   type: type,
  //   id: Info.value.id,
  // };
  if (type == 3) {
    articleShow.value = true;
    return;
  }
  router.push(`/h5/article?types=${type}&id=${route.query.id}`);
};
//产品条款
const clickArticle = (item: any, type: number) => {
  router.push(`/h5/article?types=${type}&id=${item.id}`);
};
//过滤时间
const filter = (type: any, options: any) => {
  if (type == "year") {
    return options.filter(
      (option: any) => Number(option.value) >= new Date().getFullYear()
    );
  }
  if (type == "day") {
    return filterDayDate(options);
  }
  if (type == "month") {
    return filterMonthDate(options);
  }

  return options;
};
//过滤月份
const filterMonthDate = (options: any) => {
  // console.log(filterYear.value);
  if (filterYear.value == new Date().getFullYear()) {
    return options.filter(
      (option: any) => Number(option.value) >= new Date().getMonth() + 1
    );
  } else {
    return options;
  }
};
//过滤天数
const filterDayDate = (options: any) => {
  // console.log(filterYear.value);
  if (
    filterMonth.value == new Date().getMonth() + 1 &&
    filterYear.value == new Date().getFullYear()
  ) {
    return options.filter(
      (option: any) => Number(option.value) >= new Date().getDate() + 1
    );
  } else {
    return options;
  }
};
const pickerChnage = (value: any) => {
  filterYear.value = value.selectedValues[0];
  filterMonth.value = value.selectedValues[1];
  filterDay.value = value.selectedValues[2];
  // console.log(filterYear.value);
};
//获取职业类别
const getCategory = async () => {
  const res = await getJobClassify("");
  categoryArr.value = res.msg;
};
//获取当前时间
const getDate = () => {
  let date = new Date();
  filterYear.value = new Date().getFullYear();
  filterMonth.value = date.getMonth() + 1;
  year.value = date.getFullYear(); //获取完整的年份(4位)
  month.value = date.getMonth() + 1; //获取当前月份(0-11,0代表1月)
  strDate.value = date.getDate() + 1; // 获取当前日(1-31)
  routeType.value = route.query.type as string;

  let data = [`${year.value}`, `${month.value}`, `${strDate.value}`];
  startTimer.value = year.value + "-" + month.value + "-" + strDate.value;
  getCategory();
  // console.log(routeType.value);

  return data;
};
getDate();
//获取缓存数据
const getSession = () => {
  if (sessionStorage.getItem("zj_dqyw")) {
    let key: keyof sumbitType;
    for (key in param) {
      param[key] = JSON.parse(sessionStorage.getItem("zj_dqyw") as string)[key];
    }
    let infokey: keyof infoTbrxxType;
    for (infokey in infoTbrxx) {
      infoTbrxx[infokey] = param.insure[infokey] as string;
    }
    // userArr.value = param.user as any;

    startTimer.value = param.start_time;
    endTimer.value = param.end_time;
    let star = new Date(startTimer.value).getTime();
    let end = new Date(endTimer.value).getTime();
    days.value = (end - star) / (1000 * 3600 * 24) + 1;
    if (!days.value) {
      days.value = 0;
    }

    // dataSelect.value[0].forEach((item: any, index: number) => {
    //   if (item.text == days.value) {
    //     daysIndex.value = index;
    //   }
    // });
  }
};
//获取投保页面信息
const getInfo = async () => {
  if (route.query.id && !route.query.order_id) {
    const res = await getInsureInfo({ id: route.query.id });

    Info.value = res.msg;

    //noticeShow.value = true;
    getSession();
    Info.value.duty[1].data.forEach((item: any, index: number) => {
      if (index == 1) {
        item['disabled'] = false
      } else {
        item['disabled'] = true
      }
    })
    // Info.value.duty[1].data[1]['disabled'] = false
    player()
  } else {
    sessionStorage.removeItem("zj_dqyw");
    //详情页
    const res = await orderDetail({ id: route.query.order_id });
    edit.value = false;
    let key: keyof infoTbrxxType;
    for (key in infoTbrxx) {
      infoTbrxx[key] = res.msg.insure[key];
    }

    infoCategory.category = res.msg.job_code_name;
    infoCategory.job_code = res.msg.job_code;
    // userArr.value = res.msg.user;
    param.user = res.msg.user;
    Info.value = res.msg;
    Info.value.name = res.msg.bx_info.name;
    Info.value.brand = res.msg.bx_info.brand;
    Info.value.doc = res.msg.bx_info.doc
    startTimer.value = res.msg.start_time;
    endTimer.value = res.msg.end_time;
    let star = new Date(startTimer.value).getTime();
    let end = new Date(endTimer.value).getTime();

    // param.address = res.msg.address;
    days.value = (end - star) / (1000 * 3600 * 24) + 1;
    Info.value.state = res.msg.state;
    let paramKey: keyof sumbitType;
    for (paramKey in param) {
      param[paramKey] = res.msg[paramKey];
    }
    param.add_price = Number(res.msg.add_price);
    cost.value = Number(res.msg.total_price);
  }
};
getInfo();
// 时间戳：1637244864707
/* 时间戳转换为时间 */
const timestampToTime = (timestamp: any) => {
  timestamp = timestamp ? timestamp : null;
  let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  let Y = date.getFullYear() + "-";
  let M =
    (date.getMonth() + 1 < 10 ? date.getMonth() + 1 : date.getMonth() + 1) +
    "-";
  let D = (date.getDate() < 10 ? date.getDate() : date.getDate()) + " ";

  return Y + M + D;
};

const pickerConfirm = ({
  selectedValues,
}: {
  selectedValues: any;
  selectedOptions: any;
}) => {
  if (type.value == 0) {
    startTimer.value =
      selectedValues[0] + "-" + selectedValues[1] + "-" + selectedValues[2];
    let star = startTimer.value + " 00:00:00";

    let date1 = new Date(star).getTime();

    let time = date1 - 1000 * 3600 * 24 + days.value * 1000 * 3600 * 24;
    endTimer.value = timestampToTime(time);
  } else if (type.value == 2) {
    //有效天数
    days.value = selectedValues[0];
    let data = new Date(startTimer.value).getTime();

    let endtime =
      data - 1000 * 3600 * 24 + Number(days.value) * 1000 * 3600 * 24;
    // console.log(endtime);
    endTimer.value = timestampToTime(endtime);
    endTimer.value;
    param.end_time = param.start_time + (days.value - 1) * 1000 * 3600 * 24;
    price.value = 0;
    Rate.value = costRate() as number;
    responsibilityRef.value?.list.forEach((item: any) => {
      price.value += Number(item.price);
    });
    countCost();
  }

  // if (type.value) {
  //   endTimer.value =
  //     selectedValues[0] + "-" + selectedValues[1] + "-" + selectedValues[2];
  // } else {
  //   startTimer.value =
  //     selectedValues[0] + "-" + selectedValues[1] + "-" + selectedValues[2];
  // }
  showBottom.value = false;
};
const openPicker = (i: number) => {
  //i 0是开始时间 1是结束数据 2是有效天数

  if (!edit.value) return;

  type.value = i;
  showBottom.value = true;
};
//重组数据
const setParam = () => {
  param.bx_id = route.query.id as string;
  let tbrxxKey: keyof insureType;
  for (tbrxxKey in param.insure) {
    param.insure[tbrxxKey] = tbrxxRef.value?.Info[tbrxxKey] as string;
  }
  param.address = addressVueRef.value?.addInfo.address as any;
  param.job_code = categoryRef.value?.Info.job_code;
  param.user = userRef.value?.user;
  let treekey: keyof treetopType;
  for (treekey in param.treetop) {
    param.treetop[treekey] = ysRef.value?.Info[treekey];
  }
  param.insured = fjInsuredRef.value?.list;
  param.start_time = startTimer.value;
  param.end_time = endTimer.value;
  param.duty = responsibilityRef.value?.list;
  param.annex = uploadRef.value?.uploadList;
};
const sumbit = () => {
   if (!checked.value) return showToast("请阅读协议");
  noticeShow.value = false;
  formRef.value
    ?.validate()
    .then(async (_) => {
      setParam();
      if (param.address) {
        if (param?.address?.length < 5) {
          showToast("施工地址不得少于五个字");
          return
        }
      }
      if (stopFun) {
        stopFun()
      }
      // param.add_price = Number(responsibilityRef.value?.add_price);
      const res = await addOrder(param);
      if (res.code == 1) {
        showToast("提交成功");
        sessionStorage.removeItem("zj_dqyw");
        let order_id = res.msg;

        setTimeout(() => {
          // router.push("/h5/mine/payOrder?type=1");

          edit.value = false;
          router.replace(
            `/h5/insure/zj_dqyw?id=${param.bx_id}&order_id=${order_id}&type=1`
          );
          routeType.value = "1";
          route.query.order_id = res.msg;
          getInfo();
        }, 500);
      } else {
        showToast(res.msg);
      }
    })
    .catch((_) => { });
};
//支付
const pay = async () => {
  if (edit.value) {
    //提交保单
    sumbit();
  } else {
    // 支付
    overlayShow.value = true;
    const res = await submitApi({ id: route.query.order_id });

    if (res.code == 1) {
      window.location.href = res.msg;
    } else {
      showToast(res.msg);
    }
    overlayShow.value = true;
    // console.log(res);
  }
};
const share = () => {
  router.push("/h5/insure/share?id=" + Info.value.id);
};
</script>
<style scoped lang="scss">
:deep(.van-cell-group--inset) {
  margin: 0 !important;
}

:deep(.van-field__control::-webkit-input-placeholder) {
  color: #9b9da9;
}

.ios {
  padding-bottom: constant(safe-area-inset-bottom);
}
</style>
